package com.googlecode.garbagecan.test.socket;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressUtil {
	public static byte[] compress(byte[] bytes) throws IOException {
		byte[] ret;
		ByteArrayOutputStream baos = null;
		GZIPOutputStream gzipos = null;
		try {
			baos = new ByteArrayOutputStream();
			gzipos = new GZIPOutputStream(baos);
			gzipos.write(bytes);
			gzipos.finish();
			ret = baos.toByteArray();
		} catch(IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			closeQuietly(baos);
			closeQuietly(gzipos);
		}
		return ret;
	}

	public static byte[] uncompress(byte[] bytes) throws IOException {
		byte[] ret;
		ByteArrayOutputStream baos = null;
		ByteArrayInputStream bais = null;
		GZIPInputStream gzipis = null;

		try {
			baos = new ByteArrayOutputStream();
			bais = new ByteArrayInputStream(bytes);
			gzipis = new GZIPInputStream(bais);
			byte[] buf = new byte[1024];
			while (true) {
				int size = gzipis.read(buf);
				if (size <= 0) {
					break;
				}
				baos.write(buf, 0, size);
			}
			ret = baos.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			closeQuietly(baos);
			closeQuietly(bais);
			closeQuietly(gzipis);
		}
		return ret;
	}

	private static void closeQuietly(InputStream is) {
		try {
			is.close();
		} catch (Exception e) {
		}
	}

	private static void closeQuietly(OutputStream os) {
		try {
			os.close();
		} catch (Exception e) {
		}
	}
}
